package com.tlgen.modules.system.service.impl;

import com.tlgen.common.exception.EntityExistException;
import com.tlgen.common.utils.FileUtil;
import com.tlgen.common.utils.PageUtil;
import com.tlgen.common.utils.QueryHelp;
import com.tlgen.common.utils.ValidationUtil;
import com.tlgen.modules.system.domain.CSort;
import com.tlgen.modules.system.domain.Medical;
import com.tlgen.modules.system.repository.MedicalRepository;
import com.tlgen.modules.system.service.MedicalService;
import com.tlgen.modules.system.service.dto.MedicalDto;
import com.tlgen.modules.system.service.dto.MedicalQueryCriteria;
import com.tlgen.modules.system.service.mapper.MedicalMapper;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Service
@CacheConfig(cacheNames = "medical")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class MedicalServiceImpl implements MedicalService {

    private final MedicalRepository medicalRepository;

    private final MedicalMapper medicalMapper;

    public MedicalServiceImpl(MedicalRepository medicalRepository, MedicalMapper medicalMapper) {
        this.medicalRepository = medicalRepository;
        this.medicalMapper = medicalMapper;
    }


    /**
     * 不带条件分页查询
     * @param pageable 分页参数
     * @return
     */
    @Override
    @Cacheable
    public Object queryAll(Pageable pageable) {
        return medicalMapper.toDto(medicalRepository.findAll(pageable).getContent());
    }


    /**
     * 带条件分页查询
     * @param criteria 条件
     * @param pageable 分页参数
     * @return
     */
    @Override
    @Cacheable
    public Object queryAll(MedicalQueryCriteria criteria, Pageable pageable) {
        Page<Medical> page = medicalRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(medicalMapper::toDto));
    }

    /**
     * 带条件不分页查询
     * @param criteria 条件
     * @return
     */
    @Override
    @Cacheable
    public List<MedicalDto> queryAll(MedicalQueryCriteria criteria) {
        return medicalMapper.toDto(medicalRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    /**
     * 新增
     * @param resources /
     * @return
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public MedicalDto create(Medical resources) {
        if(medicalRepository.findByName(resources.getName()) != null){
            throw new EntityExistException(Medical.class,"name",resources.getName());
        }
        return medicalMapper.toDto(medicalRepository.save(resources));
    }

    /**
     * 编辑
     * @param resources /
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void update(Medical resources) {
        Medical medical = medicalRepository.findById(resources.getId()).orElseGet(Medical::new);
        ValidationUtil.isNull(medical.getId(),"medical","id",resources.getId());

        Medical medical1 = medicalRepository.findByName(resources.getName());

        if(medical1 != null && !medical1.getId().equals(medical.getId())){
            throw new EntityExistException(CSort.class,"medical",resources.getName());
        }

        medical.setCode(resources.getCode());
        medical.setName(resources.getName());
        medical.setType(resources.getType());
        medical.setSpread(resources.getSpread());
        medicalRepository.save(medical);
    }

    /**
     * 根据Id查询
     * @param id /
     * @return
     */
    @Override
    @Cacheable(key = "#p0")
    public MedicalDto findById(long id) {
        Medical medical = medicalRepository.findById(id).orElseGet(Medical::new);
        ValidationUtil.isNull(medical.getId(),"medical","id",id);
        return medicalMapper.toDto(medical);
    }

    /**
     * 删除
     * @param ids /
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        for (Long id : ids) {
            medicalRepository.deleteById(id);
        }
    }

    /**
     * 导出数据
     * @param response /
     * @throws IOException
     */
    @Override
    public void download(List<MedicalDto> medicalDtos, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (MedicalDto medicalDto : medicalDtos) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("医疗机构编号", medicalDto.getCode());
            map.put("医疗机构名称", medicalDto.getName());
            map.put("医疗机构类型", medicalDto.getType());
            map.put("医疗机构分布", medicalDto.getSpread());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

}
